package utools

import (
	"database/sql"
	"errors"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

var (
	DB     *sql.DB
	DSN    string
	isConn bool
)

func InitDB(dsn string) error {
	if isConn {
		return nil
	}
	isConn = true
	defer func() { isConn = false }()
	if db, err := sql.Open("mysql", dsn); err != nil { //校验格式的准确性，并创建SQLDB实例
		return err
	} else {
		if err := db.Ping(); err != nil { //验证数据库是否真正的连接成功
			println("数据库连接失败，五秒后重连", err.Error())

			go func() { //自动尝试重连
				time.Sleep(5 * time.Second)
				InitDB(dsn)
			}()
			return err
		} else {
			DSN = dsn
			DB = db
			return nil
		}
	}

}

func GetDB() (*sql.DB, error) {
	if !isConn {
		err := DB.Ping()
		if err != nil {
			InitDB(DSN) //数据库下线尝试重连
		}
		return DB, nil

	} else {
		return nil, errors.New("db is not connect")
	}
}
